package com.sylar.happyreader;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aphidmobile.flip.FlipViewController;
import com.aphidmobile.flip.FlipViewController.FlipViewOnPageChange;
import com.sylar.happyreader.net.HttpTool;
import com.sylar.happyreader.page.BookPage;
import com.sylar.happyreader.tools.Config;
import com.sylar.happyreader.view.AutoText;

public class ReadFilpBookActivity extends Activity implements FlipViewOnPageChange, Runnable {
	private String sex;
	private String style;
	private String bookName;
	private FlipViewController flipView;
	private BookPage bookPage;
	private FlipAdapter flipAdapter;
	private ProgressDialog mPD;
	private boolean background = false;

	private TextView tv_book_name;
	private TextView tv_page;
	private TextView tv_power;
	private TextView tv_time;

	private PopupWindow read_menuPop;

	private LooperThread timeLooper;
	private BroadcastReceiver batteryLevelRcvr;

	public final static int UPDATE_TIME = 111;
	public final static int UPDATEBATTERY = UPDATE_TIME + 1;
	public final static int UPDATE_BOOK = UPDATEBATTERY + 1;
	public final static int UPDATE_PAGE = UPDATE_BOOK + 1;

	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_TIME:
				String[] info = (String[]) msg.obj;
				if (tv_time != null)
					tv_time.setText("时间:" + info[0] + ":" + info[1]);
				break;
			case UPDATEBATTERY:
				String level = (String) msg.obj;
				if (tv_power != null)
					tv_power.setText("电量:" + level + "%");
				break;
			case UPDATE_BOOK:
				toNextPage();
				if (mPD != null)
					mPD.dismiss();
				break;
			case UPDATE_PAGE:
				String page = (String) msg.obj;
				if (tv_page != null)
					tv_page.setText(page);
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		bookName = this.getIntent().getStringExtra("bookName");
		style = this.getIntent().getStringExtra("style");
		sex = this.getIntent().getStringExtra("sex");

		flipView = new FlipViewController(this);
		flipView.setPageChangeListener(this);

		setMenuView();

		RelativeLayout mainLayout = new RelativeLayout(getApplicationContext());
		mainLayout.addView(flipView);

		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		View read_bottom = getLayoutInflater().inflate(R.layout.read_bottom, null);
		mainLayout.addView(read_bottom, params);

		setContentView(mainLayout);

		tv_book_name = (TextView) read_bottom.findViewById(R.id.tv_book_name);
		tv_page = (TextView) read_bottom.findViewById(R.id.tv_page);
		tv_power = (TextView) read_bottom.findViewById(R.id.tv_power);
		tv_time = (TextView) read_bottom.findViewById(R.id.tv_time);

		if (timeLooper == null) {
			timeLooper = new LooperThread();
			timeLooper.start();
		}

		monitorBatteryState();

		toNextPage();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (timeLooper != null) {
			timeLooper.interrupt();
			timeLooper = null;
		}

		if (batteryLevelRcvr != null)
			unregisterReceiver(batteryLevelRcvr);
	}

	void setMenuView() {
		View read_menu = this.getLayoutInflater().inflate(R.layout.read_menu, null);
		read_menuPop = new PopupWindow(read_menu, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
	}

	class FlipAdapter extends BaseAdapter {

		private BookPage bookPage;

		public FlipAdapter(BookPage bookPage) {
			this.bookPage = bookPage;
		}

		public int getCount() {
			if (bookPage != null)
				return bookPage.getM_totalPage();
			return 0;
		}

		public List<String> getItem(int position) {
			if (bookPage != null)
				return bookPage.pageDown(position);
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			AutoText autoText;
			if (convertView == null) {
				autoText = new AutoText(getApplicationContext());
			} else {
				autoText = (AutoText) convertView;
			}
			float fPercent = (float) (position * 1.0 / getCount());
			Message msg = mHandler.obtainMessage();
			DecimalFormat df = new DecimalFormat("#0.0");
			String strPercent = df.format(fPercent * 100) + "%";
			msg.obj = strPercent;
			msg.what = UPDATE_PAGE;
			mHandler.sendMessage(msg);
			autoText.setText(getItem(position));

			return autoText;

		}

	}

	void toNextPage() {
		if (!TextUtils.isEmpty(ReadBookActivity.msg)) {
			try {
//				String pageName = Config.pagelists[Config.pageNo].trim();
//				if (tv_book_name != null)
//					tv_book_name.setText(pageName);
				Config.pageNo++;
				String content = ReadBookActivity.msg;
				ReadBookActivity.msg = null;
				bookPage = new BookPage(getApplicationContext());
				bookPage.openbook(content);
				flipAdapter = new FlipAdapter(bookPage);
				flipView.setAdapter(flipAdapter);
			} catch (Exception e) {
				e.printStackTrace();
			}
			background = true;
			new Thread(this).start();
		} else {
			this.mPD = new ProgressDialog(this);
			this.mPD.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			this.mPD.setMessage("加载中...");
			this.mPD.show();
			background = false;
			new Thread(this).start();
		}

	}

	boolean showOrCloseMenu() {
		if (read_menuPop != null && read_menuPop.isShowing()) {
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			read_menuPop.dismiss();
			return true;
		} else {
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			if (read_menuPop != null)
				read_menuPop.showAtLocation(flipView, Gravity.BOTTOM, 0, 0);
			return false;
		}
	}

	// 拦截MENU按钮
	public boolean onMenuOpened(int featureId, Menu menu) {
		showOrCloseMenu();
		return false;
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("menu");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			float downX = ev.getRawX();
			float downY = ev.getRawY();
			if (Math.abs(downX - flipView.getWidth() / 2) <= 100f & Math.abs(downY - flipView.getHeight() / 2) <= 100f) {
				showOrCloseMenu();
				return false;
			}
			break;
		}
		return super.dispatchTouchEvent(ev);
	}

	public void onPageChange(int frontCardsIndex, int backCardsIndex) {
		if (frontCardsIndex < 0) {
			 Toast.makeText(getApplicationContext(), "前面什么都木有哦", 0).show();
		} else if (backCardsIndex < 0) {
			if(Config.pagelists.length > Config.pageNo + 1){
				toNextPage();
			}else{
				Toast.makeText(getApplicationContext(), "后面什么都木有哦", 0).show();
			}
			
		}
	}

	public void run() {
		if (ReadBookActivity.msg == null || "".equals(ReadBookActivity.msg)) {

			if (Config.pagelists != null && Config.pagelists.length > Config.pageNo + 1) {
				Config.nowPage = Config.pagelists[Config.pageNo + 1];
				String url = Config.RequestUri + "sex=" + sex + "&style=" + Uri.encode(style) + "&bookName=" + Uri.encode(bookName) + "&pageCount=" + Uri.encode(Config.nowPage);
				String result = HttpTool.getString(getApplicationContext(), url);
				if (!TextUtils.isEmpty(result)) {
					result = result.replace("光影之间团队分享", "");
					result = result.replace("更多精彩内容请访问", "");
					result = result.replace("http://www.newperl.com", "");
					ReadBookActivity.msg = result;
					if (!background) {
						mHandler.sendEmptyMessage(UPDATE_BOOK);
					}
				} else {
					// 加载失败
				}
			}

		}
	}

	class LooperThread extends Thread {
		public void run() {
			super.run();
			try {
				do {// 每间隔一秒取一次系统 时间
					long time = System.currentTimeMillis();
					final Calendar mCalendar = Calendar.getInstance();
					mCalendar.setTimeInMillis(time);
					String[] info = new String[] { mCalendar.get(Calendar.HOUR_OF_DAY) + "", mCalendar.get(Calendar.MINUTE) + "" };
					Thread.sleep(1000);
					// 取得系统时间后发送消息给Handler
					Message m = new Message();
					m.what = UPDATE_TIME;
					m.obj = info;
					mHandler.sendMessage(m);
				} while (!LooperThread.interrupted());// 当系统发出终端命令时停止循环
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void monitorBatteryState() {
		batteryLevelRcvr = new BroadcastReceiver() {

			public void onReceive(Context context, Intent intent) {
				StringBuilder sb = new StringBuilder();
				int rawlevel = intent.getIntExtra("level", -1);
				int scale = intent.getIntExtra("scale", -1);
				int status = intent.getIntExtra("status", -1);
				int health = intent.getIntExtra("health", -1);
				int level = -1; // percentage, or -1 for unknown
				if (rawlevel >= 0 && scale > 0) {
					level = (rawlevel * 100) / scale;
				}
				Message msg = mHandler.obtainMessage();
				msg.obj = level + "";
				msg.what = UPDATEBATTERY;
				mHandler.sendMessage(msg);
			}
		};
		IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		registerReceiver(batteryLevelRcvr, batteryLevelFilter);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && read_menuPop != null && read_menuPop.isShowing()) {
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			read_menuPop.dismiss();
			return false;
		} else {
			finish();
		}

		return true;
	}

}
